package com.bt.framework.manager

import android.annotation.SuppressLint
import android.app.Application
import android.content.Context
import android.content.res.Resources
import android.os.Build
import android.provider.Settings
import android.util.DisplayMetrics
import android.view.WindowManager
import com.bt.framework.log.XLogger
import com.bt.framework.utils.DeviceInfoUtils
import kotlin.math.max
import kotlin.math.min

/**
 *@author:hxm
 *@date: 2025/6/22 12:05
 *@version:
 *@description:
 */
object AppManager {

    private val TAG = AppManager.javaClass.simpleName

    private lateinit var mContext: Application

    private var mScreenWidthPx = 0

    private var mScreenHeightPx = 0

    private var mScreenWidthDp = 0

    private var mScreenHeightDp = 0

    private var mDensityDpi = 0

    private var mDensity = 0f

    private var mStatusBarHeight = 0

    private var mProductType: String? = null

    private var mIsBiggerScreen = false


    @SuppressLint("InternalInsetResource")
    fun init(application: Application) {
        mContext = application
        val windowManager =
            application.getSystemService(Application.WINDOW_SERVICE) as WindowManager
        val metrics = DisplayMetrics()
        windowManager.defaultDisplay.getMetrics(metrics)
        mScreenHeightPx = max(metrics.heightPixels, metrics.widthPixels)
        mScreenWidthPx = min(metrics.heightPixels, metrics.widthPixels)
        mIsBiggerScreen = mScreenHeightPx * 0.1f / mScreenWidthPx > 16.0 / 9
        mDensityDpi = metrics.densityDpi
        mScreenHeightDp = (mScreenHeightPx / mDensityDpi).toInt()
        mScreenWidthPx = (mScreenWidthPx / mDensityDpi).toInt()

        val resourceId =
            application.resources.getIdentifier("status_bar_height", "dimen", "android")
        mStatusBarHeight = application.resources.getDimensionPixelSize(resourceId)
        mProductType = genProductType()
    }

    fun getScreenWidthPx() = mScreenWidthPx

    fun getScreenHeightPx() = mScreenHeightPx

    fun getScreenWidthDp() = mScreenWidthDp

    fun getScreenHeightDp() = mScreenHeightDp

    fun getDensity() = mDensity

    fun getStatusBarHeight() = mStatusBarHeight

    fun getProductType() = mProductType

    private fun genProductType(): String {
        val model = DeviceInfoUtils.phoneModel
        return model.replace("[:{} \\[\\]\"']*".toRegex(), "")
    }

    /**
     * 获取状态栏高度
     */
    fun getSmartBarHeight(): Int {
        if (isMeizu() && hasSmartBar()) {
            val autoHideSmartBar = Settings.System.getInt(
                mContext.contentResolver,
                "mz_smartbar_auto_hide", 0
            ) == 1
            return if (autoHideSmartBar) 0 else getNormalNavigationBarHeight()
        }
        return 0
    }

    private fun getNormalNavigationBarHeight(): Int {
        try {
            val res: Resources =
                mContext.resources
            val rid = res.getIdentifier("config_showNavigationBar", "bool", "android")
            if (rid > 0) {
                val flag = res.getBoolean(rid)
                if (flag) {
                    val resourceId =
                        res.getIdentifier("navigation_bar_height", "dimen", "android")
                    if (resourceId > 0) {
                        return res.getDimensionPixelSize(resourceId)
                    }
                }
            }
        } catch (e: Throwable) {
            e.message?.let { XLogger.e(it) }
        }
        return 0
    }

    /**
     * 判断是否魅族手机
     */
    fun isMeizu() = Build.MANUFACTURER.equals("Meizu", true)

    fun hasSmartBar(): Boolean {
        try {// 新型号可用反射调用Build.hasSmartBar()
            val method =
            Class.forName("android.os.Build").getMethod("hasSmartBar")
            return method.invoke(null) as Boolean
        } catch (e: Exception) {
            XLogger.d("hasSmartBar msg ${e.message}")
        }
        // 反射不到Build.hasSmartBar()，则用Build.DEVICE判断
        if (Build.DEVICE == "mx2") {
            return true
        } else if (Build.DEVICE == "mx" || Build.DEVICE == "m9") {
            return false
        }
        return false
    }

    /**
     * 是否是 屏
     */
    fun isBiggerScreen() = mIsBiggerScreen

    /**
     * 获取手机品牌
     */
    fun getDeviceBuildBrand() = Build.BRAND ?: ""

    /**
     * 获取手机型号
     */
    fun getDeviceBuildMode() = DeviceInfoUtils.phoneModel

    /**
     * 获取手机系统SDK版本
     */
    fun getDeviceBuildRelease() = Build.VERSION.RELEASE ?: ""

    /**
     * dp转px
     */
    fun dip2Px(dip: Float) = (dip * mDensity + 0.5f).toInt()

    /**
     * 获取当前App版本名
     */
    fun getAppVersionName(context: Context): String {
        var appVersionName: String = ""
        try {
            val packageName = context.packageName ?: "com.sum.tea"
            val pi = context.applicationContext.packageManager.getPackageInfo(packageName, 0)
            appVersionName = pi.versionName.toString()
            if (appVersionName.isEmpty()) {
                return ""
            }
        } catch (e: Exception) {
            XLogger.d("getAppVersionName failure ${e.message}")
        }
        return appVersionName
    }

    /**
     * 获取当前app版本号
     */
    @SuppressLint("NewApi")
    fun getAppVersionCode(context: Context): Long {
        var appVersionCode: Long = 0L
        try {
            val packageName = context.packageName ?: "com.sum.tea"
            val packageInfo =
                context.applicationContext.packageManager.getPackageInfo(packageName, 0)
            appVersionCode = packageInfo.longVersionCode
        } catch (e: Exception) {
            XLogger.e("getAppVersionCode-${e.message}")
        }
        return appVersionCode
    }

    override fun toString(): String {
        return ("PhoneInfoManager{" +
                "mScreenWidthPx=" + mScreenWidthPx + "," +
                "mScreenHeightPx=" + mScreenHeightPx + "," +
                "mScreenWidthDp=" + mScreenWidthDp + "," +
                "mScreenHeightDp=" + mScreenHeightDp + "," +
                "mDensityDpi=" + mDensity + "," +
                "mStatusBarHeight=" + mStatusBarHeight + "," +
                "}")
    }

}